import requests
from lxml import etree
import json
import  openpyxl
import re

url = "https://voice.baidu.com/act/newpneumonia/newpneumonia"
respone = requests.get(url)

#print(respone.text)
html = etree.HTML(respone.text)
result = html.xpath('//script[@type="application/json"]/text()')
#
result = result[0]
result = json.loads(result)

wb = openpyxl.Workbook()
ws = wb.active
ws.tit1e = "国内疫情"
ws.append(['省份',"累计确诊","死亡","治愈","现有确诊","累计确诊增量","死亡增量","治愈增量","现有确诊增量"])


result_in = result['component'][0]['caseList']
result_out = result['component'][0]['globalList']
# print(result_out)
for each in  result_in:
    # print(each)
    # print('*'*50+'\n')
    temp_list = [each['area'], each['confirmed'], each['died'], each['crued'], each['curConfirm'] , each['confirmedRelative'], each['diedRelative'], each['curedRelative'], each['curConfirmRelative']]
    ws.append(temp_list)
    for i in range(len(temp_list)):
        if temp_list[i] == "":
            temp_list[i] = '0'
    ws.append(temp_list)
for each in result_out:
    # print(each)
    # print("\n" + '*' * 20)
    sheet_title = each['area']
    # 创建一个新的工作表
    ws_out = wb.create_sheet(sheet_title)
    ws_out.append(['国家', '累计确诊', '死亡', '治愈', '现有确诊', '累计确诊增量'])
    for country in each['subList']:
        list_temp = [country['country'], country['confirmed'], country['died'], country['crued'],
                     country['curConfirm'], country['confirmedRelative']]
        for i in range(len(list_temp)):
            if list_temp[i] == '':
                list_temp[i] = '0'
        ws_out.append(list_temp)


wb.save('./data.xlsx')
